var express = require("express");
var router = express.Router();
const jwt = require('jsonwebtoken');
//const mysql = require('mysql');
const axios = require("axios");
const fs = require("fs");
const path = require("path");
const configs = require("../config");
const crypto = require("crypto");
// 微信小程序配置
const APPID = "wxca0a9c4169a80590"; // 替换为你的小程序 AppID
const APPSECRET = "0160d2527e5630861195707cd002c600"; // 替换为你的小程序 AppSecret
const mysql = require("mysql2/promise");

const SECRET_KEY = configs.token.SECRET_KEY; // 用于签名 Access Token
const REFRESH_SECRET_KEY = configs.token.REFRESH_SECRET_KEY; // 用于签名 Refresh Token
// 创建数据库连接池
const pool = mysql.createPool({
  host: configs.mysql.host,
  user: configs.mysql.user,
  password: configs.mysql.password,
  database: configs.mysql.database,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
});
/**
 * 解密手机号
 * @param {string} sessionKey - 微信 session_key
 * @param {string} encryptedData - 加密数据
 * @param {string} iv - 解密算法的初始向量
 * @returns {string} - 解密后的手机号
 */
function decryptPhoneNumber(sessionKey, encryptedData, iv) {
  const sessionKeyBuffer = Buffer.from(sessionKey, "base64");
  const encryptedDataBuffer = Buffer.from(encryptedData, "base64");
  const ivBuffer = Buffer.from(iv, "base64");

  try {
    const decipher = crypto.createDecipheriv(
      "aes-128-cbc",
      sessionKeyBuffer,
      ivBuffer
    );
    decipher.setAutoPadding(true);
    let decoded = decipher.update(encryptedDataBuffer, "binary", "utf8");
    decoded += decipher.final("utf8");
    const data = JSON.parse(decoded);
    return data.phoneNumber; // 返回解密后的手机号
  } catch (err) {
    throw new Error("解密失败");
  }
}

/**
 * 获取微信 session_key
 * @param {string} code - 微信登录凭证 code
 * @returns {Promise<string>} - session_key
 */
async function getSessionKey(code) {
  const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${APPID}&secret=${APPSECRET}&js_code=${code}&grant_type=authorization_code`;
  const response = await axios.get(url);
  if (response.data.errcode) {
    throw new Error(response.data.errmsg);
  }
  return response.data.openid;
}

/**
 * 处理获取手机号的请求
 * POST /login/getPhoneNumber
 * 请求体：
 * {
 *   "code": "微信登录凭证 code",
 *   "encryptedData": "加密数据",
 *   "iv": "解密算法的初始向量"
 * }
 */
router.post("/getPhoneNumber", async (req, res) => {
  const { iv, encryptedData, code } = req.body;

  if (!iv || !encryptedData || !code) {
    return res.status(400).json({ error: "缺少必要参数" });
  }

  try {
    // 获取 session_key
    const sessionKey = await getSessionKey(code);
    // 解密手机号
    const phoneNumber = decryptPhoneNumber(sessionKey, encryptedData, iv);
    res.json({ phoneNumber });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

router.post("/getSessionKey/:code", async (req, res) => {
  const code = req.params.code;

  if (!code) {
    return res.status(400).json({ error: "缺少必要参数" });
  }

  try {
    // 获取 session_key
    const sessionKey = await getSessionKey(code);
    // 把sessionKey.data.sessionKey 最为 openid 存入 yzUser 表
    const openid = sessionKey;
// 生成 Access Token（短期有效）
const accessToken = jwt.sign({ userId: openid }, SECRET_KEY, { expiresIn: '15m' });

// 生成 Refresh Token（长期有效）
const refreshToken = jwt.sign({ userId: openid }, REFRESH_SECRET_KEY, { expiresIn: '7d' });
    // 查询yzUser表中是否存在openid
    const sql = 'SELECT openid,username,useravatar FROM yzUser WHERE openid = ?';
    const [result] = await pool.query(sql, [openid]);
    if (result.length > 0) {
      return res.json({
        status: "操作成功",
        code: 200,
        data: result,
        refreshToken,
        accessToken
      });
    } else {
      //随即生成一个用户名 格式： 用户+openid后4位
      const username = "用户" + openid.substring(6, 11);

      const sql = `INSERT INTO yzUser (openid,username,useravatar) VALUES ('${openid}','${username}','https://ztapp-1304966785.cos.ap-nanjing.myqcloud.com/%E9%BB%98%E8%AE%A4%E5%A4%B4%E5%83%8F.svg')`;
      const result = await pool.query(sql);
      //返回插入 的数据
      const sql2 = `SELECT openid,username,useravatar FROM yzUser WHERE openid = '${openid}'`;
      const [result2] = await pool.query(sql2);

      res.json({
        status: "操作成功",
        code: 200,
        data: result2,
        refreshToken,
        accessToken
      });
    }
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});
router.post('/refreshtoken', (req, res) => {
  const { refreshToken } = req.body;

  if (!refreshToken) {
      return res.status(401).json({ message: 'Refresh Token is missing' });
  }

  jwt.verify(refreshToken, REFRESH_SECRET_KEY, (err, user) => {
      if (err) {
          return res.status(403).json({ message: 'Refresh Token is invalid or expired' });
      }

      // 生成新的 Access Token
      const newAccessToken = jwt.sign({ userId: user.userId }, SECRET_KEY, { expiresIn: '15m' });

      // 可选：生成新的 Refresh Token
      const newRefreshToken = jwt.sign({ userId: user.userId }, REFRESH_SECRET_KEY, { expiresIn: '7d' });

      //res.json({ accessToken: newAccessToken, refreshToken: newRefreshToken });
      res.json({
        status: "操作成功",
        code: 200,
        data: { accessToken: newAccessToken, refreshToken: newRefreshToken },
       
      });
  });
});

// 将 router 对象导出，以便在其他模块中使用
module.exports = router;
